#include <Wire.h>

uint8_t outbuf[6];
uint8_t storebuf[150];
int cnt = 0;
int ledPin = 13;

int cnt2 = 0;
void
receiveEvent (int howMany)
{
int a =0;
  while (Wire.available ())
    {
      a++;
      uint8_t c = Wire.receive (); // receive byte as a character
      storebuf[ cnt ] = c;
      cnt++;
      if ( cnt > 97) {
          print();
      }
   storebuf[ cnt ] = a;
   cnt++;
      digitalWrite (ledPin, HIGH);    // sets the LED on
    }
    

}

void print()
{
   
   int s = 0;
   Serial.println ("start data dump");
   Serial.println (cnt,DEC);
   while ( s < (cnt -1 ) ) {
      Serial.print (storebuf[ s ],DEC);
      s++;
   }
   Serial.println ("end data dump");
   cnt = 0;
}

void
requestEvent ()
{
  outbuf[0] = nunchuk_encode_byte (125);  // joystick X
  outbuf[1] = nunchuk_encode_byte (126);  // joystick Y
  outbuf[2] = nunchuk_encode_byte (227);  // Axis X
  outbuf[3] = nunchuk_encode_byte (241);  // Axis Y
  outbuf[4] = nunchuk_encode_byte (140);  // Axis Z
  outbuf[5] = nunchuk_encode_byte (1);  // Press C button, byte[5] is buttons C and Z,
                                        //and accelaration data
  //outbuf[5] = nunchuk_encode_byte(2); // Press Z button
  //outbuf[5] = nunchuk_encode_byte(0); // Press Z and C button
  storebuf[ cnt ] = 88;
  cnt++;   
  Wire.send (outbuf, 6);        // send data packet
 
}

void
setup ()
{
  pinMode (ledPin, OUTPUT); 
  beginSerial (19200);
  Serial.print ("setup\n");

  Wire.begin (0x52);            // join i2c bus with address 0x52
                                // this is the nunchuk address.
                                // all nunchuks use this address
  Wire.onReceive (receiveEvent);        // register event
  Wire.onRequest (requestEvent);        // register event
}

void
loop ()
{
   
  //delay (100);
}


// Encode data to format that most wiimote drivers except
// only needed if you use one of the regular wiimote drivers
char
nunchuk_encode_byte (char x)
{
  x = x - 0x17;
  x = (x ^ 0x17);
  return x;
}
